package com.sky.zzh.today;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import cn.sharesdk.onekeyshare.OneKeyShareCallback;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.zzh.R;
import com.sky.zzh.today.date.SliderContainer;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;
import com.sky.zzh.view.CalendarDialog;
import com.sky.zzh.view.CalendarDialog.CalendarResultListener;

/**
 * Created by Steve on 2015/9/15.
 */
public class TodayDetailMainActivity extends Activity
    implements
      OnFragmentInteractionListener,
      ITaskListener {
  public static final int TYPEGETUP = 1;
  public static final int TYPETURNUP = 2;

  protected Calendar mInitialTime, minTime = null, maxTime = null;
  protected int mLayoutID;
  protected SliderContainer mContainer;
  protected int minuteInterval;
  private SliderContainer.OnTimeChangeListener onTimeChangeListener;

  // ////////////////////////////////////////////

  private FragmentManager fragmentManager;
  private FragmentTransaction fragmentTransaction;
  private int type = 1;

  // 诊断的信息
  private TextView textViewConclusion;
  // 切换是离床还是体动
  private TextView textViewTitle;
  // 切换离床还是体动的图标
  private ImageView iconGetUp;
  // 显示频率
  private TextView textViewRate;
  // 调用日历
  private ImageView ic_menology;
  // 往上翻月
  private ImageView ic_Resize;
  private TextView textViewDate;
  private TodayOnclickListener mTodayOnclickListener;
  private ToggleButton mToggleButton;
  private Button toggleMenuButton;
  private SHGet getDataTask, getAssessmentListTask;
  private TextView tv_title;
  private LinearLayout llReport;
  private Button share;

  // /detail
  private TextView textViewDetailzhenduan;
  private TextView textViewDetailjieshi;
  private TextView textViewDetailAdvice;



  private String outOfBedRate = "N/A";
  private String moveMentRate = "N/A";
  private String conclusion = "N/A";
  private int startHour = 6;
  private int endHour = 4;
  private String startDate = "20150926";
  private String endDate = "20150627";
  IFragment fragment = null;
  private boolean isShowReport = false;
  // /////
  private int assessmentCode = 1001;
  private String advice = null;
  private String detail = null;


  // ////
  private HashMap<Integer, ArrayList<String>> advices = new HashMap<Integer, ArrayList<String>>();

  // 查询数据
  private void requestData(String fromDate, String endDate) {
    if (getDataTask != null) {
      getDataTask.cancel(true);
    }
    getDataTask = new SHGet();
    getDataTask.setListener(this);
    getDataTask.setUrl(ConfigDefinition.URL + "app/SleepQuality");
    getDataTask.getTaskArgs().put("UUID",UserInfoManager.getInstance().getUUID());
//    getDataTask.getTaskArgs().put("UUID", "MT003");
    System.out.println("UUID:" + UserInfoManager.getInstance().getUUID());
    getDataTask.getTaskArgs().put("UserId", UserInfoManager.getInstance().getUserId());
    getDataTask.getTaskArgs().put("FromDate", fromDate);
    getDataTask.getTaskArgs().put("EndDate", endDate);
    getDataTask.getTaskArgs().put("FromTime", URLEncoder.encode("18:00"));
    getDataTask.getTaskArgs().put("EndTime", URLEncoder.encode("18:00"));

    getAssessmentListTask = new SHGet();
    getAssessmentListTask.setUrl(ConfigDefinition.URL + "app/AssessmentList");
    getAssessmentListTask.getTaskArgs().put("UUID", UserInfoManager.getInstance().getUUID());
//    getAssessmentListTask.getTaskArgs().put("UUID", "MT003");
    getAssessmentListTask.getTaskArgs().put("UserId", UserInfoManager.getInstance().getUserId());
    getAssessmentListTask.setListener(this);
    getAssessmentListTask.start();



  }

  private String getSDCardPath() {
    File sdcardDir = null;
    boolean sdcardExist =
        Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    if (sdcardExist) {
      sdcardDir = Environment.getExternalStorageDirectory();
    }
    return sdcardDir.toString();
  }

  private void showShare(boolean silent, String platform, boolean captureView) {
    final OnekeyShare oks = new OnekeyShare();

    // oks.setAddress("12345678901");
    oks.setTitle("智照护");
    // oks.setTitleUrl("http://mob.com");
    oks.setText("");
    oks.setImagePath(getSDCardPath() + "/zzh/ScreenImages" + "/Screen_share.png");
    // oks.setImagePath(CustomShareFieldsPage.getString("imagePath",
    // MainActivity.TEST_IMAGE));
    // oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/05/21/oESpJ78_533x800.jpg");
    // oks.setImageArray(new String[]{MainActivity.TEST_IMAGE,
    // MainActivity.TEST_IMAGE_URL});

    // oks.setUrl("http://www.mob.com");
    // oks.setFilePath(CustomShareFieldsPage.getString("filePath",
    // MainActivity.TEST_IMAGE));
    // oks.setComment(CustomShareFieldsPage.getString("comment",
    // context.getString(R.string.share)));
    // oks.setSite(getActivity().getResources().getString(R.string.app_name));
    // oks.setSiteUrl("http://mob.com");
    // oks.setVenueName(CustomShareFieldsPage.getString("venueName",
    // "ShareSDK"));
    // oks.setVenueDescription(CustomShareFieldsPage.getString("venueDescription",
    // "This is a beautiful place!"));
    // oks.setLatitude(23.056081f);
    // oks.setLongitude(113.385708f);
    oks.setSilent(silent);
    // oks.setShareFromQQAuthSupport(shareFromQQLogin);
    oks.setTheme(OnekeyShareTheme.CLASSIC);

    if (platform != null) {
      oks.setPlatform(platform);
    }

    // 令编辑页面显示为Dialog模式
    oks.setDialogMode();

    // 在自动授权时可以禁用SSO方式
    // if(!CustomShareFieldsPage.getBoolean("enableSSO", true))
    oks.disableSSOWhenAuthorize();

    // 去除注释，则快捷分享的操作结果将通过OneKeyShareCallback回调
    oks.setCallback(new OneKeyShareCallback());

    // 为EditPage设置一个背景的View
    // oks.setEditPageBackground(getPage());
    oks.show(this);
  }

  private void GetandSaveCurrentImage() {
    SHDialog.ShowProgressDiaolg(this, "正在截图...");
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    int w = display.getWidth();
    int h = display.getHeight();
    Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
    View decorview = getWindow().getDecorView();
    decorview.setDrawingCacheEnabled(true);
    Bmp = decorview.getDrawingCache();
    String SavePath = getSDCardPath() + "/zzh/ScreenImages";
    try {
      File path = new File(SavePath);
      String filepath = SavePath + "/Screen_share.png";
      File file = new File(filepath);
      if (!path.exists()) {
        path.mkdirs();
      }
      if (!file.exists()) {
        file.createNewFile();
      }
      FileOutputStream fos = null;
      fos = new FileOutputStream(file);
      if (null != fos) {
        Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.flush();
        fos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    SHDialog.dismissProgressDiaolg();
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_today_main);
    mTodayOnclickListener = new TodayOnclickListener();
    textViewConclusion = (TextView) findViewById(R.id.textViewConclusion);
    textViewRate = (TextView) findViewById(R.id.textViewRate);
    textViewTitle = (TextView) findViewById(R.id.textViewTitle);
    iconGetUp = (ImageView) findViewById(R.id.iconGetUp);
    ic_Resize = (ImageView) findViewById(R.id.ic_Resize);
    ic_menology = (ImageView) findViewById(R.id.ic_menology);
    ic_menology.setOnClickListener(mTodayOnclickListener);
    textViewDate = (TextView) findViewById(R.id.textViewDate);
    mToggleButton = (ToggleButton) findViewById(R.id.toggleButtonSwicthClass);
    toggleMenuButton = (Button) findViewById(R.id.toggleMenuButton);
    toggleMenuButton.setOnClickListener(mTodayOnclickListener);
    tv_title = (TextView) findViewById(R.id.tv_title);
    llReport = (LinearLayout) findViewById(R.id.llReport);
    textViewDetailAdvice = (TextView) findViewById(R.id.textViewDetailAdvice);
    textViewDetailzhenduan = (TextView) findViewById(R.id.textViewDetailzhenduan);
    textViewDetailjieshi = (TextView) findViewById(R.id.textViewDetailjieshi);
    share = (Button) findViewById(R.id.btn_right);
    share.setOnClickListener(mTodayOnclickListener);
    if (isShowReport) {
      ic_Resize.setBackgroundResource(R.drawable.ic_s_resize);
    } else {
      ic_Resize.setBackgroundResource(R.drawable.ic_sresize);
    }

    if (UserInfoManager.getInstance().isCustomer()) {
      mToggleButton.setTag("ENABLE");
    } else {
      mToggleButton.setTag("DISABLE");
    }

    mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO 设置起始和结束的时间，用来切换表格的数据
        String tag = (String) mToggleButton.getTag();
        if (tag.equals("DISABLE")) {
          mToggleButton.setChecked(false);
          Toast.makeText(getApplicationContext(), "请到睡眠设置中打开自定义睡眠", Toast.LENGTH_SHORT).show();
        } else {
          mToggleButton.setTag("ENABLE");
          if (isChecked) {
            // 24小时
            startHour = 6;
            endHour = 4;
            mToggleButton.setBackgroundResource(R.drawable.ic_24hours);
          } else {
            mToggleButton.setBackgroundResource(R.drawable.ic_user_defined);
            if (UserInfoManager.getInstance().isCustomer()) {
              // 自定义
              String startString = UserInfoManager.getInstance().getStartTime();
              String endString = UserInfoManager.getInstance().getEndTime();
              if (startString != null && endString != null) {
                startHour = getHour(startString);
                endHour = getHour(endString);
              }
            }
          }
          onSwitchBetween24Custom(startHour, endHour);

        }

      }
    });
    ic_Resize.setOnClickListener(mTodayOnclickListener);
    type = getIntent().getExtras().getInt("TYPE");
    if (type == TYPEGETUP) {
      textViewRate.setText(outOfBedRate);
    } else if (type == TYPETURNUP) {
      textViewDate.setText(moveMentRate);
    }
    textViewConclusion.setText(conclusion);
    fragmentManager = getFragmentManager();
    // 切换表格数据的fragment，默认的起始时间
    activeFragment(startHour, endHour, startDate, endDate, true);
    //
    mContainer = (SliderContainer) findViewById(R.id.dateSliderContainer);
    onTimeChangeListener = new SliderContainer.OnTimeChangeListener() {
      // 时间改变的时候回调
      public void onTimeChange(Calendar time) {
        setTitle();
      }
    };
    initSliderDate();
  }

  private int getHour(String string) {
    String[] split = string.split(":");
    return Integer.valueOf(split[0]);
  }

  private void initSliderDate() {
    mInitialTime = Calendar.getInstance();
    mContainer.setOnTimeChangeListener(onTimeChangeListener);
    mContainer.setMinuteInterval(minuteInterval);
    mContainer.setTime(mInitialTime);
    if (minTime != null) {
      mContainer.setMinTime(minTime);
    }
    if (maxTime != null) {
      mContainer.setMaxTime(maxTime);
    }
  }



  // 切换图表数据
  public void activeFragment(int startHour, int endHour, String startDate, String endDate,
      boolean isDefault) {
    if (type == TYPEGETUP) {
      textViewTitle.setText("离床");
      iconGetUp.setImageResource(R.drawable.ic_leave);
      fragment = GetUpFragment.newInstance(startHour, endHour, startDate, endDate, true);
    } else if (type == TYPETURNUP) {
      textViewTitle.setText("体动");
      iconGetUp.setImageResource(R.drawable.ic_turn);
      fragment = TurnFragment.newInstance(startHour, endHour, startDate, endDate);
    }
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.rl_chart, fragment);
    fragmentTransaction.commit();
  }

  @Override
  public void onFragmentInteraction(String string) {}

  private class TodayOnclickListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
      switch (v.getId()) {
        case R.id.ic_Resize:
          isShowReport = !isShowReport;
          if (isShowReport) {
            tv_title.setText("诊断报告");
            ic_Resize.setBackgroundResource(R.drawable.ic_s_resize);
            llReport.setVisibility(View.VISIBLE);
            ObjectAnimator valueAnimato = ObjectAnimator.ofFloat(llReport, "scaleY", 0f, 1f);
            valueAnimato.start();
          } else {
            tv_title.setText("");
            ic_Resize.setBackgroundResource(R.drawable.ic_sresize);
            ObjectAnimator valueAnimato = ObjectAnimator.ofFloat(llReport, "scaleY", 1f, 0f);
            valueAnimato.start();
          }
          break;
        case R.id.toggleMenuButton:
          onBackPressed();
          break;
        case R.id.ic_menology:
          CalendarDialog dia =
              new CalendarDialog(TodayDetailMainActivity.this, new CalendarResultListener() {
                Calendar calendar = Calendar.getInstance();

                @Override
                public void onCalendarResult(Dialog d, String date) {
                  // TODO Auto-generated method stub
                  d.dismiss();
                  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                  try {
                    Date dd = format.parse(date);
                    calendar.setTime(dd);
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;
                    int day = calendar.get(Calendar.DAY_OF_MONTH);
                    textViewDate.setText(year + "年" + month + "月");
                    mContainer.setTime(calendar);

                  } catch (ParseException e) {
                    e.printStackTrace();
                  }
                }
              });
          dia.show();
          break;
        case R.id.btn_right:
          GetandSaveCurrentImage();
          showShare(false, null, false);
          break;
        default:
          break;
      }

    }
  }


  /**
   * @return The currently displayed time
   */
  protected Calendar getTime() {
    return mContainer.getTime();
  }

  public void setTime(Calendar c) {
    mContainer.setTime(c);
  }

  /**
   * 
   * TODO 可能需要加上网络请求，将切换页面等放在这个方法中
   * 
   */
  protected void setTitle() {
    if (textViewDate != null) {
      final Calendar c = getTime();
      // mTitleText.setText("dateSliderTitle" + String.format(": %te. %tB %tY", c, c, c));
      int year = c.get(Calendar.YEAR);
      int month = c.get(Calendar.MONTH) + 1;
      int day = c.get(Calendar.DAY_OF_MONTH);
      String text = year + "年" + month + "月";
      textViewDate.setText(text);
      endDate = year + "" + CommonUtil.getDoubleNum(month) + "" + CommonUtil.getDoubleNum(day);
      startDate = CalendarUtil.getPrevious(year, month, day);
      requestData(startDate, endDate);
    }
  }

  private void onSwitchBetween24Custom(int startHour, int endHour) {
    activeFragment(startHour, endHour, startDate, endDate, true);
  }



  @Override
  public void onTaskFinished(SHTask task) throws Exception {
    JSONObject json = new JSONObject(task.getResult().toString());
    // 获取的是离床的数据
    if (task == getDataTask) {
      System.out.println("getDataTask:" + json);
      try {
        if ("200".equals(json.optString("ReturnCode"))) {
          String bedrate = json.optString("OutOfBedTimes");
          if (TextUtils.isEmpty(bedrate)) {
            bedrate = "0";
          }
          outOfBedRate = bedrate + "次/天";
          String moveRate = json.optString("BodyMovementTimes");
          if (TextUtils.isEmpty(moveRate)) {
            moveRate = "0";
          }
          moveMentRate = moveRate + "次/天";
          int quality = json.optInt("SleepQuality");
          assessmentCode = json.optInt("AssessmentCode");
          if (assessmentCode == 0) {
            conclusion = "还没有数据，快躺到床上来";
            advice = "还没有数据，快躺到床上来";
            detail = "还没有数据，快躺到床上来";
          } else {
            conclusion = advices.get(assessmentCode).get(1);
            advice = advices.get(assessmentCode).get(0);
            detail = advices.get(assessmentCode).get(2);
          }


          JSONArray array = json.optJSONArray("Data");
          if (array.length() != 0) {
            JSONObject obj = array.getJSONObject(0);
            String SleepStartTime = obj.optString("SleepStartTime");
            String SleepEndTime = obj.optString("SleepEndTime");
          }
          // 设置频率和诊断信息
          textViewConclusion.setText(conclusion);
          if (type == 1) {
            textViewRate.setText(outOfBedRate);
          } else {
            textViewRate.setText(moveMentRate);
          }
          if (fragment != null) {
            // /切换数据表格
            activeFragment(startHour, endHour, startDate, endDate, false);
          }
        } else {
          textViewRate.setText("还没有数据，快躺到床上来");
          textViewConclusion.setText("还没有数据，快躺到床上来");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      textViewDetailzhenduan.setText(conclusion);
      textViewDetailAdvice.setText(advice);
      textViewDetailjieshi.setText(detail);
    }

    if (task == getAssessmentListTask) {
      System.out.println("getAssessmentListTask:" + json);
      JSONArray array = json.optJSONArray("Assessments");
      JSONObject obj = null;
      int size = array.length();
      for (int i = 0; i < size; i++) {
        ArrayList<String> list = new ArrayList<String>();
        obj = array.getJSONObject(i);
        int code = obj.optInt("Code");
        list.add(obj.optString("Suggestion"));
        list.add(obj.optString("Conclusion"));
        list.add(obj.optString("Description"));
        advices.put(code, list);
      }
      getDataTask.start();
    }

  }

  private String getQuality(int value) {
    String s = "非常好";
    switch (value) {
      case 5:
        s = "非常好";
        break;
      case 4:
        s = "好";
        break;
      case 3:
        s = "正常";
        break;
      case 2:
        s = "差";
        break;
      case 1:
        s = "非常差";
        break;
      default:
        break;
    }
    return s;
  }


  @Override
  public void onTaskFailed(SHTask task) {}

  @Override
  public void onTaskUpdateProgress(SHTask task, int count, int total) {}

  @Override
  public void onTaskTry(SHTask task) {}
}
